package com.yjd.back.system.control;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageDecoder;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.yjd.comm.base.control.BaseControl;
import com.yjd.comm.base.enums.DbWREnums;
import com.yjd.comm.base.model.Model;
import com.yjd.comm.base.model.ResultModel;
import com.yjd.comm.fs.model.FileUploadedModel;
import com.yjd.comm.fs.util.FtpAllUtil;
import com.yjd.comm.system.model.AdminModel;
import com.yjd.comm.system.service.IAdminService;
import com.yjd.comm.util.FrameUtil;
import com.yjd.comm.util.OSSClientUtil;
import com.yjd.comm.util.ServletUtil;
import com.yjd.comm.util.ServletUtil.UrlTypeEnum;
import com.yjd.comm.util.StaticAndPicsUtil;
import com.yjd.comm.vo.Constant.ResultEnum;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

@Controller
@Scope("prototype")
@RequestMapping("/upload/")
public class UploadControl extends BaseControl {
	@Resource
	private IAdminService adminService;

	@SuppressWarnings("unchecked")
	@RequestMapping("uploadImg")
	public void upload(MultipartHttpServletRequest request) throws Exception {
		Map<String, MultipartFile> mulFileMap = request.getFileMap();
		MultipartFile dfi = mulFileMap.get("Filedata");
		String originalName = dfi.getOriginalFilename();
		String uid = request.getParameter("uid");
		String sign = request.getParameter("sign");
		FileUploadedModel fum = null;
		if (this.uploadAuthor(uid, sign)) {
			File temp = new File(request.getSession().getServletContext()
					.getRealPath("/temp/")
					+ "java" + getRandomString(5));
			FileUtils.copyInputStreamToFile(dfi.getInputStream(), temp);
			String remotefile = "editor/"+FrameUtil.getTime(null) + "" + getRandomString(12)
					+ originalName.substring(originalName.lastIndexOf("."));

			String uploadType = FrameUtil.getConstResource("uploadType");
			if("oss".equals(uploadType)){

				fum  = OSSClientUtil.uploadFile2OSS(temp,remotefile);
				fum.setAttachurl(StaticAndPicsUtil.getPicsDataFullUrl(remotefile, true));
				fum.setName(originalName.substring(0, originalName.length()
						- fum.getExt().length() - 1));
				temp.delete();
			}
			if("static".equals(uploadType)){
				fum = FtpAllUtil.uploadFileItem(temp, FrameUtil.getConstResource("FTP.remotePath")+remotefile);
				fum.setAttachurl(ServletUtil.getUrl1("/"+remotefile, UrlTypeEnum.PICS,
						null, null));
				temp.delete();
			}
		}
		if (fum != null) {
			ResultModel rm = new ResultModel(ResultEnum.SUCCESS, null,
					FrameUtil.getResource("文件上传成功！"), null);
			rm.setData(fum.getMap());

			ServletUtil.outputJsonMessage(response, rm.toMap());
		} else {
			this.errorMsg(null, "文件上传失败！");
		}
	}

	/**
	 * 
	 * 上传用户认证材料
	 * 
	 * @param request
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("upUserCheck")
	public void upUserCheck(MultipartHttpServletRequest request)
			throws Exception {
		Map<String, MultipartFile> mulFileMap = request.getFileMap();
		if (mulFileMap.size() == 0) {
			this.errorMsg(null, "上传文件不能为空!");
		}
		MultipartFile dfi = mulFileMap.get("Filedata");
		String originalName = dfi.getOriginalFilename();
		String[] uids = request.getParameter("uid").split("\\|");
		// 管理员id
		String adminId = uids[0];
		// 会员id
		String userId = uids[1];
		String sign = request.getParameter("sign");
		FileUploadedModel fum = null;
		// 验证签名
		if (this.uploadAuthor(adminId, sign)) {
			StringBuilder filePath = new StringBuilder(
					StaticAndPicsUtil.getPicsDataDir());
			long userIdl = Long.parseLong(userId);
			filePath.append(Math.round(Math.ceil((double)userIdl / 10000)))
					.append("/")
					.append(Math.round(Math.ceil((double)userIdl % 10000 / 1000)))
					.append("/")
					.append(userIdl)
					.append("/")
					.append(UUID.randomUUID().toString())
					.append(originalName.substring(originalName
						.lastIndexOf(".")));
			File temp = new File(request.getSession().getServletContext()
					.getRealPath("/temp/")
					+ UUID.randomUUID().toString());
			FileUtils.copyInputStreamToFile(dfi.getInputStream(), temp);
			addWatetImage(temp.getPath());//图片添加水印

			String uploadType = FrameUtil.getConstResource("uploadType");
			if("oss".equals(uploadType)){

				fum  = OSSClientUtil.uploadFile2OSS(temp,filePath.toString());
				fum.setAttachurl(StaticAndPicsUtil.getPicsDataFullUrl(filePath.toString(), true));
				fum.setName(originalName.substring(0, originalName.length()
						- fum.getExt().length() - 1));
				temp.delete();
			}
			if("static".equals(uploadType)){
				fum = FtpAllUtil.uploadFileItem(temp, FrameUtil.getConstResource("FTP.remotePath")+filePath.toString());
				fum.setAttachurl(StaticAndPicsUtil.getPicsDataFullUrl(
					filePath.toString(), true));
				fum.setName(originalName.substring(0, originalName.length()
						- fum.getExt().length() - 1));
				temp.delete();

			}
			if (fum != null) {
				ResultModel rm = new ResultModel(ResultEnum.SUCCESS, null,
						FrameUtil.getResource("文件上传成功！"), null);
				rm.setData(fum.getMap());
				ServletUtil.outputJsonMessage(response, rm.toMap());
			} else {
				this.errorMsg(null, "文件上传失败！");
			}
		}


	}

	public String getRandomString(int length) { // length表示生成字符串的长度
		String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < length; i++) {
			int number = random.nextInt(base.length());
			sb.append(base.charAt(number));
		}
		return sb.toString();
	}

	public boolean uploadAuthor(String uid, String sign)
			throws NumberFormatException, Exception {
		boolean flag = false;
		Model m = this.adminService.getModelById(Long.parseLong(uid),DbWREnums.READ);
		String password = ((AdminModel) m).getPassword();
		flag = sign.equals(DigestUtils.md5Hex(password + uid));
		return flag;
	}
	
	/**
	 * 跟图片添加水印
	 * @param fileName
	 * @throws Exception
	 */
	public void addWatetImage(String fileName) throws Exception {
		if (StringUtils.isBlank(fileName)) {
			return;
		}
		InputStream inputStream = null;
		OutputStream os = null;
		try {
			inputStream = new FileInputStream(fileName);
			//通过JPEG图象流创建JPEG数据流解码器
			JPEGImageDecoder jpegDecoder = JPEGCodec.createJPEGDecoder(inputStream);
			//解码当前JPEG数据流，返回BufferedImage对象
			BufferedImage buffImg = jpegDecoder.decodeAsBufferedImage();
			//得到画笔对象
			Graphics g = buffImg.getGraphics();
			//水印图片小图片的路径
			String waterFile = this.getClass().getClassLoader().getResource("").getPath() + "yijiedai.png";
			ImageIcon imgIcon = new ImageIcon(waterFile);
			//得到Image对象。
			Image img = imgIcon.getImage();
			//将小图片绘到大图片上。
			ImageIcon targetIcon = new ImageIcon(fileName);
			g.drawImage(img, targetIcon.getIconWidth() / 2 - 100, targetIcon.getIconHeight() / 2 - 35, null);
			os = new FileOutputStream(fileName);
			//创键编码器，用于编码内存中的图象数据。
			JPEGImageEncoder en = JPEGCodec.createJPEGEncoder(os);
			en.encode(buffImg);
		}finally {
			IOUtils.closeQuietly(os);
			IOUtils.closeQuietly(inputStream);
		}
	}
}
